/** @file download.h
    @brief Image downloader */
#ifndef QRV_DOWNLOAD_H
#define QRV_DOWNLOAD_H

#include <string>
#include <fstream>
#include <sstream>
#include <vector>

#include <time.h>
#include <stdlib.h>

#include <curl/curl.h>

//! \todo Use QT networking instead of libCURL
//! \todo Download full-size pictures instead of thumbnails
//! \todo Make the downloader more configurable (not only numbers, but random words as well)

/** @class Downloader
    @brief Image downloader class */
class Downloader {
	public:
		Downloader();
		~Downloader();

		/**
			@brief Initializes CURL
		*/
		bool init();

		/**
			@brief Fetches an image
			@return Path to the stored image
		*/
		std::string fetch();

	private:
		/**
			@brief Queries for images, downloads the results
			@return Path to the file into which query result was temporarily saved
		*/
		std::string query();

		/**
			@brief Parses the query result
			@param[in] s_path Reference to the path of the query dump
			@return Vector of image paths found from the query
		*/
		std::vector< std::string > parse( const std::string &s_path );

		/**
			@brief Downloads an image
			@param[in] s_image Reference to the URL of the image
			@return Path of the image that was downloaded
		*/
		std::string download( const std::string &s_image );

		/**
			@brief Gets a path for a file with a given URL
			@param[in] s_url Reference to the URL of the file
			@return Path to the file - where it's to be downloaded
		*/
		std::string get_dest( const std::string &s_url );
		
		/**
			@brief Checks if the given string is a valid image URL
			@param[in] s_url Reference to the URL to be validated
			@return Valid URL or empty string
		*/
		std::string validate_regular_image( const std::string &s_url );
		
		/**
			@brief Checks if the given string is a valid Google Static image URL
			@param[in] s_url Reference to the URL to be validated
			@return Valid URL or empty string
		*/
		std::string validate_gstatic_image( const std::string &s_url );

		/**
			@brief Checks if the given URL is valid or if it's possible to fix it
			@param[in] s_url Reference to the URL to be validated
			@return Valid URL or empty string
		*/
		std::string validate_url( const std::string &s_url );
		
		/**
			@brief Checks if the given path points to a valid image file and
			renames the file based on file format, if necessary
			@param[in] s_path Reference to the path to be validated
			@return Valid path or empty string
		*/
		std::string validate_image_file( const std::string &s_path);

		//! CURL pointer
		CURL *m_curl;
};

#endif

